//
//  PushFriendsViewController.m
//  Liuhe
//
//  Created by zr on 2018/8/13.
//  Copyright © 2018年 zr. All rights reserved.
//

#import "PushFriendsViewController.h"
#import "PushInfoTableViewCell.h"
#import "InfoOthersTableViewCell.h"
#import "PushFriendsInfoHeader.h"


@interface PushFriendsViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
    
    UIImagePickerController *_imagePickerController;
}

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSArray * titleArray;
@property (nonatomic, strong)NSArray * textFiledArray;
@property (nonatomic, strong)PushFriendsInfoHeader * headerView;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, copy)NSString * images;
//===
@property (nonatomic, copy)NSString * myName;
@property (nonatomic, copy)NSString * mySex;
@property (nonatomic, copy)NSString * myAge;
@property (nonatomic, copy)NSString * myHeight;
@property (nonatomic, copy)NSString * myWeight;
@property (nonatomic, copy)NSString * myJob;
@property (nonatomic, copy)NSString * myHome;
@property (nonatomic, copy)NSString * myEducation;
@property (nonatomic, copy)NSString * myIncome;
@property (nonatomic, copy)NSString * exploreStr;
@property (nonatomic, copy)NSString * reqrire_age;
@property (nonatomic, copy)NSString * reqrire_income;
@property (nonatomic, copy)NSString * reqrire_education;
@property (nonatomic, copy)NSString * reqrire_house;
@property (nonatomic, copy)NSString * myTel;
@property (nonatomic, copy)NSString * myEmail;


@end

@implementation PushFriendsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = WHITE_COLOR;
    //,@"",@"",@"",@"",@"",@""
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(GetPicture) name:@"GetPicture" object:nil];
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    
    self.titleArray = @[@"我的名字:",@"我的性别:",@"我的年龄:",@"我的身高:",@"我的体重:",@"我的职业:",@"我的籍贯:",@"我的学历:",@"我的收入:",@"详情描述:",@"年龄要求:",@"收入要求:",@"学历要求:",@"住房要求:",@"我的联系电话:",@"我的邮箱:"];
    self.textFiledArray = @[@"名字",@"1 男 2 女",@"岁",@"cm",@"平方",@"",@"请输入",@"请选择",@"请选择",@"",@"",@"",@"",@"",@"",@""];
    
    [self setupNav];
    [self setupUI];
    [self setupAlertVC];
}


- (void)setupNav{
    
    self.title = @"发布信息";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(0, 0, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
    
    UIButton * backButton1 = [[UIButton alloc] init];
    
    //    backButton.frame = CGRectMake(0 , 0 , 65 * SCREENH6, 20 * SCREENH6);
    [backButton1 setTitle:@"发布" forState:UIControlStateNormal];
    backButton1.titleLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
    [backButton1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [backButton1 addTarget:self action:@selector(ClickSureButton) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * nextButton = [[UIBarButtonItem alloc] initWithCustomView:backButton1];
    
    self.navigationItem.rightBarButtonItem = nextButton;
    
}

- (void)backToView{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)setupUI{
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT - 64) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor whiteColor];
//    tableView.rowHeight = 45 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[PushInfoTableViewCell class] forCellReuseIdentifier:@"PushInfoListCell"];
    
    [self.tableView registerClass:[InfoOthersTableViewCell class] forCellReuseIdentifier:@"InfoOthersListCell"];
    [self.tableView registerClass:[PushFriendsInfoHeader class] forHeaderFooterViewReuseIdentifier:@"PushFriendsInfoHeaderView"];
    
    [self.view addSubview:self.tableView];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return self.titleArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 9) {
        
        InfoOthersTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InfoOthersListCell" forIndexPath:indexPath];
        
        cell.titleLabel.text = self.titleArray[indexPath.row];
        
        cell.block = ^(NSString * text) {
            
            self.exploreStr = text;
        };
        
        return cell;
        
    }else{
        
        PushInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PushInfoListCell" forIndexPath:indexPath];
        
        cell.titleLabel.text = self.titleArray[indexPath.row];
        cell.textFiled.placeholder = self.textFiledArray[indexPath.row];
        if (indexPath.row == 0) {
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.myName = text;
            };
        } else if (indexPath.row == 1) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.mySex = text;
            };
        } else if (indexPath.row == 2) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.myAge = text;
            };
        }else if (indexPath.row == 3) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.myHeight = text;
            };
        }else if (indexPath.row == 4) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.myWeight = text;
            };
        }else if (indexPath.row == 5) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.myJob = text;
            };
        }else if (indexPath.row == 6) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.myHome = text;
            };
        }else if (indexPath.row == 7) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.myEducation = text;
            };
        }else if (indexPath.row == 8) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.myIncome = text;
            };
        }else if (indexPath.row == 10) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.reqrire_age = text;
            };
        }else if (indexPath.row == 11) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.reqrire_income = text;
            };
        }else if (indexPath.row == 12) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.reqrire_education = text;
            };
        }else if (indexPath.row == 13) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.reqrire_house = text;
            };
        }else if (indexPath.row == 14) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.myTel = text;
            };
        }else if (indexPath.row == 15) {
            // 同上，请自行脑补
            cell.block = ^(NSString * text) {
                // 更新数据源
                self.myEmail = text;
            };
        }
        
        return cell;
    }
  
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 9) {
        
        return 133 * SCREENH6;
    }else{
        
        return 45 * SCREENH6;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 125 * SCREENH6;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    self.headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"PushFriendsInfoHeaderView"];
    
    return self.headerView;
}


- (void)GetPicture{
    
     [self presentViewController:self.alertVC animated:YES completion:nil];
}

- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo

{
    
    [self.headerView.addPictureButton setImage:image forState:UIControlStateNormal];
    
    NSData *frontImageData = UIImageJPEGRepresentation(image,0.5);
    
    NSString * token = DEF_GET_OBJECT(@"token");
    
    NSDictionary * dic = @{@"files":frontImageData,@"token":token};
    
    [[NetworkTool sharedTools] POST:@"/index/Note/noteupload" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat  = @"yyyyMMddHHmmss";
        NSString *str  = [formatter stringFromDate:[NSDate date]];
        NSString *fileName  = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:frontImageData name:@"files" fileName:fileName mimeType:@"image/png"];
        
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        NSLog(@"===%@",responseObject);
        
        NSInteger code = [responseObject[@"status"] integerValue];
        
        if (code == 200){
            
            self.images = [NSString stringWithFormat:@"%@",responseObject[@"data"]];
        }else{
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//进入拍摄页面点击取消按钮

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


- (void)ClickSureButton{
    
    NSString * user_id = DEF_GET_OBJECT(@"user_id");
    NSString * token = DEF_GET_OBJECT(@"token");
    
    if (self.mySex.length > 0 && self.myName.length > 0) {
        
        NSDictionary * dict = @{@"token":token,@"user_id":user_id,@"age":self.myAge,@"height":self.myHeight,@"weight":self.myWeight,@"work":self.myJob,@"native":self.myHome,@"education":self.myEducation,@"income":self.myIncome,@"signature":self.exploreStr,@"require_age":self.reqrire_age,@"require_income":self.reqrire_income,@"require_education":self.reqrire_education,@"require_house":self.reqrire_house,@"mobile":self.myTel,@"email":self.myEmail,@"name":self.myName,@"sex":self.mySex,@"headimg":self.images};
        
        
        [[NetworkTool sharedTools] POST:@"/index/Liuheonline/friendAdd" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //        NSLog(@"====%@",responseObject);
            
            int status = [responseObject[@"status"] intValue];
            
            if (status == 200) {
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:@"恭喜你，发布成功！快去看看吧！"
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          [self.navigationController popViewControllerAnimated:YES];
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseObject[@"msg"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }else{
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"请先完善信息！"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  //响应事件
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
